<template>
    <div>
        <div class="newTask-header" v-if="!updatapage">
            <van-nav-bar title="发布任务" left-text="返回" right-text="" left-arrow @click-left="onClickLeft" />
        </div>
        <div class="newTask-header" v-else>
            <van-nav-bar title="发布任务" left-text="返回" right-text="删除" left-arrow @click-left="onClickLeft"
                @click-right="onclickright(_id)" />
        </div>
        <!-- 自定义标签 -->
        <div style="padding: 10px 15px;">
            <van-form>
                <van-field v-model="titlename" center clearable name="名称" label="名称" placeholder="请输入任务名称" />
                <van-field v-model="placename" center clearable name="地点" label="地点" placeholder="请输入任务地点" />
                <van-field v-model="price" type="number" name="单价" label="单价" placeholder="请输入任务单价" />
                <van-field v-model="label" center clearable label="关键字标签" placeholder="请输入自定义关键字标签">
                    <template #button>
                        <van-button size="small" type="primary" @click="ensure">确定</van-button>
                    </template>
                </van-field>
            </van-form>
            <div class="selectlabel">
                <div class="selectlabel-mycheckbox">
                    <div class="mycheckbox">
                        <!-- 标签选择 -->
                        <van-checkbox @click="arrpush(item)" :aria-checked="selectcheckbox[index]"
                            v-model="selectcheckbox[index]" v-for="(item,index) in checked">{{item}}</van-checkbox>
                    </div>
                </div>
            </div>
        </div>
        <!-- 标签展示 -->
        <div class="showTag">
            <van-tag type="warning" @close="closeTag(item)" closeable size="medium" v-for="(item,index) in select"
                :key="index">{{item}}</van-tag>
        </div>
        <!-- 任务时间 -->
        <optionbtn :option-name="'选择日期'" @onclick="selecttime" :previewContent="currentDate" />
        <optionbtn :option-name="'具体时间'" @onclick="selecttime" :previewContent="currenthours" />
        <!-- 任务详情  -->
        <div class="editor">
            <vue-html5-editor :content="content" @change="updateData" :height="200"></vue-html5-editor>

        </div>
        <van-button round block type="info" @click="onSubmit">提交</van-button>
        <!-- 弹出层 -->
        <van-popup v-model="show" position="bottom" :style="{ height: '50%' }">
            <van-datetime-picker v-if="selectstate == '选择日期'" type="month-day" title="选择月日" :min-date="minDate"
                :max-date="maxDate" @confirm="confirm" />
            <van-datetime-picker v-else @confirm="confirmhours" type="time" title="选择时间" :min-hour="0" :max-hour="24" />
        </van-popup>
    </div>
</template>
<script>
import optionbtn from '@/components/optionsbutton.vue';
import { Taskinfo, delTask, reqTask } from "@/axios/index.js";
import { Notify } from 'vant';
import { mapState } from "vuex";
export default {
    components: {
        optionbtn
    },
    data() {
        return {
            updatapage: false,
            _id: '00',
            updata: 'noupdata',
            titlename: '',
            placename: '',
            price: null,
            label: '',
            checked: ['跑腿', '取快递', '代购', '出租', '租赁', '出售'],//循环的标签
            selectcheckbox: [0, 0, 0, 0, 0, 0],
            select: [],
            content: '',
            currentDate: null,//接收选择的日期
            selectstate: null,
            currenthours: '',//接收的具体时间
            show: false,
            minDate: new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()),
            maxDate: new Date(new Date().getFullYear(), new Date().getMonth() + 2, new Date().getDate())
        }
    },
    computed: {
        ...mapState(['user'])
    },
    methods: {
        onclickright(id) {//删除任务
            console.log(id);
            delTask({
                id
            }).then(res => {
                Notify({ type: 'success', message: res.msg });
                this.$router.push('/home/publish/updataTask')
                reqTask().then((res) => {
                    // console.log(res);
                    this.tasklist = res.data.reqTask
                    let parser = JSON.stringify(res.data.reqTask)
                    window.sessionStorage.setItem('TaskList', parser)
                })
            })
        },
        onClickLeft() {//头部返回的路由按钮
            this.$router.push('/home/publish')
        },
        updateData(a) {//富文本改变时的函数
            console.log(a);
            this.content = a
        },
        arrpush(item) {//把标签添加进数组
            let indexval = this.select.indexOf(item)
            console.log(this.select);
            if (this.select.length >= 2) {
                if (indexval >= 0) {
                    this.select.splice(indexval, 1)
                    return
                }
                let index = this.checked.indexOf(item)
                console.log(item);
                this.selectcheckbox[index] = false
                let i = this.select.splice(-1, 1)
                this.select.push(i[0])
                // this.closeTag(item)
                // console.log(this.selectcheckbox);
                return
            }
            if (indexval >= 0) {
                this.select.splice(indexval, 1)
                return
            } else if (this.select.length >= 2) {
                Notify({ type: 'danger', message: '最多指定两个关键字标签' });
                let index = this.checked.indexOf(item)
                this.selectcheckbox[index] = false
                return
            }
            this.select.push(item)
            console.log(this.select);
        },
        ensure() {//自定义标签添加进数组
            // console.log(this.label);
            if (this.select.length >= 2) {
                Notify({ type: 'danger', message: '最多指定两个关键字标签' });
                return
            }
            this.select.push(String(this.label))
            this.label = null
            console.log(this.select);
        },
        closeTag(item) {//取消标签
            console.log(item);
            let index = this.checked.indexOf(item)
            let idx = this.select.indexOf(item)
            if (index < 0) {

                if (idx < 0) return
                this.select.splice(idx, 1)
                return
            }
            this.selectcheckbox[index] = false
            this.select.splice(idx, 1)

        },
        selecttime(name) {//添加时间
            console.log(name);
            this.selectstate = name
            this.show = true
        },
        confirm(val) {//点击完成按钮
            // console.log(val);
            let month = val.getMonth() + 1//获取月份
            let days = val.getDate()
            // console.log(month+'月'+days+'日');
            this.currentDate = `${new Date().getFullYear()}年${month}月${days}日`
            this.show = false
        },
        confirmhours(val) {
            // console.log(val);
            let newtime = String(val).replace(':', '时')
            // console.log(newtime);
            this.currenthours = `${newtime}分`
            // console.log(this.currenthours);
            this.show = false
        },
        onSubmit() {
            // console.log(this.select);
            let TaskInfo = {
                title: this.titlename,//标题
                place: this.placename,//地点
                price: this.price,
                select: this.select,//标签
                content: this.content,//详情
                currentDate: this.currentDate,//日期
                hours: this.currenthours,//时间
                userinfo: this.user,
                updata: this.updata,//是否为修改
                _id: this._id//需要修改的id
            }
            for (let key in TaskInfo) {
                console.log(TaskInfo[key]);
                // console.log();
                TaskInfo[key] == this._id
                break
                if (!TaskInfo[key]) {
                    Notify('请把空余选项补全')
                    return
                }
            }
            //请求后端返回数据提交给数据库
            Taskinfo({
                TaskInfo
            }).then((res) => {
                Notify({ type: 'success', message: res.msg });
                setTimeout(() => {
                    this.$router.push('/home/publish')
                }, 1000)
                reqTask().then((res) => {
                    // console.log(res);
                    this.tasklist = res.data.reqTask
                    let parser = JSON.stringify(res.data.reqTask)
                    window.sessionStorage.setItem('TaskList', parser)
                })
            })

            // console.log(this.user);
            // 清空数据缓存

            // this.select = []
            // this.selectcheckbox = []
        }
    },
    beforeMount() {
        // console.log(this.$route);
        if (Reflect.ownKeys(this.$route.query).length !== 0) {
            console.log('修改');
            let { title, place, price, select, content, currentDate, hours, _id } = this.$route.query
            this.select = select
            this.titlename = title
            this.placename = place
            this.price = price
            this.content = content
            this.currentDate = currentDate
            this.currenthours = hours
            this.updata = true
            this._id = _id
            this.updatapage = true
        }
    }
}
</script>
<style lang="less" scoped>
.selectlabel {

    padding: 10px 0;
    box-sizing: border-box;
    overflow: hidden;

    .selectlabel-mycheckbox {
        overflow-x: scroll;
        width: 100vw;

        .mycheckbox {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 10px 15px 10px 15px;
            width: 600px;
            // width: 500px;
            // overflow: hidden;
        }
    }

}

.showTag {
    display: flex;
    gap: 5px;
    padding: 10px 15px;
}
</style>